package com.gxa.ehome.web.servlet;
import com.alibaba.fastjson.JSON;
import com.gxa.ehome.dao.BaseDao;
import com.gxa.ehome.dao.UserDao;
import com.gxa.ehome.entity.User;
import com.gxa.ehome.util.DBUtil;
import com.gxa.ehome.util.JsonResult;
import com.gxa.ehome.util.ResponseUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "UploadServlet",urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码为utf-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        FileItemFactory factory = new DiskFileItemFactory();

        // 文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        JsonResult jsonResult = new JsonResult();
        // 解析请求信息，获取所有的表单元素(文本/日期/图片/file)
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        }
        catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 对请求信息进行判断
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            //利用迭代器获取每一个表单提交的元素(其实我们只会上传file)
            FileItem item = (FileItem) iter.next();
            // 信息为文件格式
            if (!item.isFormField()) {
                String fileName = item.getName();//获得上传图片的名称
              //利用UUID生成文件名,把-去掉,后缀名用源文件后缀
                //重新对文件名进行加工

                UUID uuid = UUID.randomUUID();
                // UUID常常会把-去掉
                String replace = uuid.toString().replace("-", "");

//               String afile=fileName.substring(0,fileName.indexOf(".")) +replace.substring(8)+fileName.substring(fileName.indexOf("."));
//                System.out.println(afile);//打印文件名用来测试的
                String afile=replace.substring(0,8)+fileName;//uuidname.png


                String basePath =  request.getSession().getServletContext().getRealPath("/image/upload");
               // System.out.println(basePath);//打印当前位置
                String aa="/image/upload/"+afile;
                File file = new File(basePath, afile);
                try {
                    //核心操作

                    item.write(file);
                    //服务器返回处理之后的文件名:/upload/UUIDname.png

                    jsonResult.setCode("0");
                    jsonResult.setValue("img",aa);

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                ResponseUtil.send(response, JSON.toJSONString(jsonResult.getValues()));
            }
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
